package booksManagement;

import java.util.List;
import exceptions.*;
import booksManagement.Book;
import jpaUtils.JPAUtil;
import javax.persistence.EntityManager;

public class DvdDAO
{
	public boolean isEmpty(){
		EntityManager entityManager=JPAUtil.getEntityManager();
		if (entityManager.createNamedQuery("findAllDVDs").getResultList().isEmpty())
			return true;
		else
			return false;	
	}





	/**
	 */
	public List<DVD> getContent(){
		EntityManager entityManager=JPAUtil.getEntityManager();
		return ((List<DVD>)entityManager.createNamedQuery("findAllDVDs").getResultList());
	}






	public boolean add(DVD dvd){
			EntityManager entityManager=JPAUtil.getEntityManager();
	try{
				entityManager.persist(dvd);
			} catch (Exception e) {
				System.err.println("Problem when saving");
				e.printStackTrace();
				return false;
			}
			return true;
		}








		public String toString(){
			EntityManager entityManager=JPAUtil.getEntityManager();
			String result="";
			List<DVD> theDVDs = (List<DVD>) entityManager.createNamedQuery("findAllDVDs").getResultList();
			for (DVD d : theDVDs)
				result += d.toString()+ "\n";
					return result;
		}







		/**
		 */
		public DVD get(long dvdId) throws BookExistsException {
			EntityManager entityManager=JPAUtil.getEntityManager();
			DVD d = (DVD) entityManager.find(DVD.class, dvdId);
			if (d ==null) throw new BookExistsException();
			else return d;
		}






		/**
		 */
		public long size(){
			EntityManager entityManager=JPAUtil.getEntityManager();
			return (entityManager.createNamedQuery("findAllDVDs").getResultList().size());
		}






		/**
		 */
		public boolean remove(DVD dvd) throws BookExistsException {
			EntityManager entityManager=JPAUtil.getEntityManager();
			if (dvd== null) 
				throw new BookExistsException(); 
			else 
				try{
					entityManager.remove(dvd);
				} catch (Exception pe) {
					System.err.println("problem when deleting an entity ");
					pe.printStackTrace();
					return false;
				}
			return true;	
		}





			
			/**
			 */
			public boolean contains(DVD dvd) throws BookExistsException {
				EntityManager entityManager=JPAUtil.getEntityManager();
				if (dvd == null) throw new BookExistsException();
				DVD d = (DVD) entityManager.find(DVD.class, dvd.getIsan());
				if (d ==null) return false;
				else return d.equals(dvd);	
			}


}
